#!/usr/bin/python
#-*- coding:utf-8 -*-

import paho.mqtt.client as mqtt
import ssl
import json
import time

#连接的回调函数
def on_connect(client,userdata,flags,rc):
    print("Connect with result code"+str(rc))
    #client.subscribe(topic, qos=0)
    #------------------------需要调用的函数----------------------------------#
    pub_test(client)   
    print("ok")
        
#接收到消息回调函数
def on_message(client,userdata,msg):
    print(msg.topic+" "+str(msg.payload))
    #client.subscribe(topic, qos=0)
    #client.publish(topic,)
#发布消息的回调函数
def on_publish(msg,rc):
    if rc==0:
        print("publish msg:"+msg)
    else:
        print("error when publish msg:"+msg)
#连接配置
user = "**********"
pwd = "**********"
hostip = "127.0.0.1"
port = 8888


client = mqtt.Client()
#设置证书
client.tls_set("ca.crt", certfile=None, keyfile=None,cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLSv1_2,ciphers=None) #设置认证文件
client.tls_insecure_set(True)
#设置用户名、密码
client.username_pw_set(user,pwd)
client.connect(hostip,port,60)


def pub_test(client):
    topic='test'
    msg='hello'
    client.publish(topic,payload=msg,qos=2,retain=False)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()